贪心算法运用于背包问题(C++实现)

贪心法的基本思路:从问题的某一个初始解出发逐步逼近给定的目标,以尽可能快的地求得更好的解。当达到某算法中的某一步不能再继续前进时,算法停止。
该算法存在问题:
1. 不能保证求得的最后解是最佳的;
2. 不能用来求最大或最小解问题;
3. 只能求满足某些约束条件的可行解的范围。

贪心算法的运用-背包问题

背包问题和0/1背包问题的主要区别就是物品可不可以再分割。背包问题中的物品可以再进行分割,而0/1背包问题中的物品则反之。贪心算法往往只从局部去考虑问题,所以在解决0/1背包问题时得不到最优解。

贪心算法运用于背包问题的c++实现:

物品
 A
 B
 C
 D
 F
 
重量
 1
 2
 3
 4
 5
 
价值
 3
 10
 6
 3
 5
 

程序代码: view plaincopy to clipboardprint?
//GreedyAlgorithm.h  
#include<iostream>  
using namespace std;  
 
class GreedyAlgorithm{  
public:  
    GreedyAlgorithm(int _weight[],int _value[],int capacity);  
    double *ComputeRatio();  
    void SortRatio(double _Ratio[]);  
    double ComputeProfit();  
private:  
    int *weight;  
    int *value;  
    int capacity;  
    double profit;  
};  
//GreedyAlgorithm.cpp  
#include"GreedyAlgorithm.h"  
 
//================================  
//函数名称:GreedyAlgorithm  
//函数功能:初始化对象  
//函数参数说明:_weight[] 物品重量,_value[] 物品价值,_capacity 背包容量  
//函数返回值:void  
//创建时间:2009-04-28  
//更新:  
//================================  
GreedyAlgorithm::GreedyAlgorithm(int _weight[],int _value[],int _capacity){  
      
    this->weight=_weight;  
    this->value=_value;  
    this->capacity=_capacity;  
    this->profit=0;  
    return;  
}  
 
//====================

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用贪心算法解决普通背包问题的C++代码: ```cpp #include <iostream> #include <algorithm> using namespace std; struct goods { int weight; int value; double ratio; }; bool cmp(goods a, goods b) { return a.ratio > b.ratio; } double knapsack(goods* items, int n, int capacity) { sort(items, items + n, cmp); int current_weight = 0; double current_value = 0.0; for (int i = 0; i < n; ++i) { if (current_weight + items[i].weight <= capacity) { current_weight += items[i].weight; current_value += items[i].value; } else { int remaining_capacity = capacity - current_weight; current_value += items[i].ratio * remaining_capacity; break; } } return current_value; } int main() { int n, capacity; cout << "请输入物品数量和背包容量:" << endl; cin >> n >> capacity; goods* items = new goods[n]; cout << "请输入每个物品的重量和价值:" << endl; for (int i = 0; i < n; ++i) { cin >> items[i].weight >> items[i].value; items[i].ratio = (double)items[i].value / items[i].weight; } double result = knapsack(items, n, capacity); cout << "可以装进背包的最大价值为:" << result << endl; delete[] items; return 0; } ``` 在此代码中,我们定义了一个结构体 `goods` 来表示物品,其中包括重量、价值和价值与重量比值三个成员变量。在 `cmp` 函数中,我们按照价值与重量比值从大到小排序。在 `knapsack` 函数中,我们首先对物品数组按照价值与重量比值从大到小排序,然后从大到小依次将物品放入背包中,直到背包装满为止。如果当前物品不能完全放入背包中,则将其部分放入背包中,并相应地计算价值。最后返回背包中的总价值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值